package ar.com.ford.it.fullEconomics.persistence.dao;

import java.io.FileNotFoundException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.LinkedList;
import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import oracle.toplink.queryframework.ReadAllQuery;
import oracle.toplink.sessions.Session;
import oracle.toplink.tools.sessionmanagement.SessionManager;
import org.apache.commons.lang.StringUtils;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr03Agreement;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr04Agreemitem;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.AgreementFindStruct;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;
import com.ford.it.persistence.PersistenceManager;
import com.ford.it.persistence.Query;
import com.ford.it.persistence.Transaction;

public class AgreementDao extends Dao {
    private static final String CLASS_NAME = CommodityDao.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /**
     * Crea el request pasado por parametro
     * 
     * @param request
     * @throws PersistenceException
     */
    public void createAgreement(Teesr03Agreement agreement)
            throws PersistenceException {

        String METHOD_NAME = "createAgreement";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = null;

        tx = PersistenceUtil.getTransaction();
        tx.registerInsert(agreement);

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Busca todos los request diltrando pro los parametros pasados en el
     * findStruct
     * 
     * @param findStruct
     * @return
     * @throws PersistenceException
     */
    public Collection<Teesr03Agreement> findAgreements(
                                                       AgreementFindStruct findStruct)
            throws PersistenceException {

        String METHOD_NAME = "findAgreements";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesr04Agreemitem> requestItemColl = null;
        Collection<Teesr03Agreement> resultCol = new LinkedList<Teesr03Agreement>();
        PersistenceManager pm = null;

        pm = PersistenceUtil.getPersistenceManager();
        Query query;
        if (findStruct.getCommodity() != -1
                || !findStruct.getPartClass().equalsIgnoreCase("-1")
                || !StringUtils.isBlank(findStruct.getPrefix())
                || !StringUtils.isBlank(findStruct.getBase())
                || !StringUtils.isBlank(findStruct.getSuffix())) {
            query = pm.newQuery("findAgreementItems", Teesr04Agreemitem.class);
            query.setParameters(findStruct);
            requestItemColl = (Collection) pm.executeQuery(query);
            for (Teesr04Agreemitem item : requestItemColl) {
                if (!resultCol.contains(item.getTeesr03Agreement()))
                    resultCol.add(item.getTeesr03Agreement());
            }
        } else {
            query = pm.newQuery("findAgreements", Teesr03Agreement.class);
            query.setParameters(findStruct);
            resultCol = (Collection) pm.executeQuery(query);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return resultCol;
    }

    /**
     * Devuelve un request para ser modificado por el logic
     * 
     * @param code
     * @param plant
     * @return
     * @throws PersistenceException
     */
    public Teesr03Agreement getAgreementForUpdate(Teess01Supplier supplier,
                                                  Timestamp ecoLevel,
                                                  Teesg01Plant plant)
            throws PersistenceException {

        String METHOD_NAME = "getAgreementForUpdate";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesr03Agreement result = null;
        Teesr03Agreement pk = new Teesr03Agreement();
        pk.setTeess01Supplier(supplier);
        pk.setEesr03AgreeEcolevelDateY(ecoLevel);
        pk.setEesr03PlantCodeC(plant);
        result = (Teesr03Agreement) super.getObjForUpdate(pk);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * Borra el price increase request pasado por parametro
     * 
     * @param req
     * @throws PersistenceException
     */
    public void deleteAgreement(Teesr03Agreement agreement)
            throws PersistenceException {

        String METHOD_NAME = "deleteAgreement";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = PersistenceUtil.getTransaction();
        if (tx != null) {
            tx.registerDelete(agreement);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    public Teesr03Agreement findPrevAgreement(Teesr03Agreement agreement)
            throws PersistenceException {
        String METHOD_NAME = "findPrevAgreement";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesr03Agreement> resultCol = null;
        Teesr03Agreement result = null;
        Session session = null;

        try {
            session = SessionManager.getManager().getSession(
                    this.getSessionName());
        } catch (FileNotFoundException e) {
            throw new PersistenceException(e);
        }
        ExpressionBuilder builder = new ExpressionBuilder();
        ReadAllQuery query = new ReadAllQuery(Teesr03Agreement.class);

        Expression exp = null;

        // comparo el agreement
        exp = builder.get("eesr03PlantCodeC").equal(
                agreement.getEesr03PlantCodeC());
        exp = exp.and(builder.get("teess01Supplier").equal(
                agreement.getTeess01Supplier()));
        exp = exp.and(builder.get("eesr03AgreeEffectiveDateY").lessThan(
                agreement.getEesr03AgreeEffectiveDateY()));

        query.addOrdering(builder.get("eesr03AgreeEffectiveDateY")
                .descending());
        query.setSelectionCriteria(exp);

        resultCol = (Collection<Teesr03Agreement>) session.executeQuery(query);
        if(!resultCol.isEmpty())
            result = resultCol.iterator().next();

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

}
